import json
import os

from django.http import JsonResponse

from wardrobePlus.settings import STATIC_ROOT, IMAGES_URL
from wardrobe_plus.models import Cloth
from wardrobe_plus.serializers import ClassSerializer
from wardrobe_plus.utils import write_image_to_local


def show(request):
    cloth_list = ClassSerializer(Cloth.objects.all(), many=True)
    return JsonResponse({"cloth_list": cloth_list.data})


def search(request):
    try:
        with open(os.path.join(STATIC_ROOT, "username_mapping.json"), encoding="utf8") as f:
            username_mapping = json.loads(f.read())
    except Exception as e:
        print(f"mapping文件读取失败：{e}")
        username_mapping = {}
    try:
        json_data = json.loads(request.body)
        cloth_id = json_data.get("cloth_id", "")
        user = json_data.get("user", "")
        cloth_type = json_data.get("cloth_type", "")
        describe = json_data.get("describe", "")
        for standard_name, name in username_mapping.items():
            user = standard_name if user in name else user
        search_cloth = Cloth.objects.all()
        if cloth_id != "":
            search_cloth = search_cloth.filter(cloth_id=cloth_id)
        if user != "":
            search_cloth = search_cloth.filter(user=user)
        if cloth_type != "":
            search_cloth = search_cloth.filter(cloth_type__icontains=cloth_type)
        if describe != "":
            search_cloth = search_cloth.filter(describe__icontains=describe)
        json_search_cloth = ClassSerializer(search_cloth, many=True)
    except Exception as e:
        return JsonResponse({"code": -1, "message": f"查询失败：{e}"})
    return JsonResponse({"code": 0, "message": f"查询成功", "cloth_list": json_search_cloth.data})


def insert(request):
    try:
        with open(os.path.join(STATIC_ROOT, "username_mapping.json"), encoding="utf8") as f:
            username_mapping = json.loads(f.read())
    except Exception as e:
        print(f"mapping文件读取失败：{e}")
        username_mapping = {}
    try:
        json_data = json.loads(request.body)
        user = json_data.get("user", "")
        for standard_name, name in username_mapping.items():
            user = standard_name if user in name else user
        json_data["user"] = user
        new_cloth = Cloth.objects.create(**json_data)
        new_cloth.save()
    except Exception as e:
        return JsonResponse({"code": -1, "message": f"新增失败：{e}"})
    return JsonResponse({"code": 0, "message": f"新增成功"})


def update(request):
    try:
        json_data = json.loads(request.body)
        cloth_object = Cloth.objects.filter(cloth_id=json_data.get("cloth_id", ""))
        if cloth_object.count() == 0:
            return JsonResponse({"code": -1, "message": f"更新失败：数据库中无此cloth id"})
        cloth_object.first().update(**json_data)
    except Exception as e:
        return JsonResponse({"code": -1, "message": f"删除失败：{e}"})
    return JsonResponse({"code": 0, "message": f"删除成功"})


def delete(request):
    try:
        json_data = json.loads(request.body)
        cloth_object = Cloth.objects.filter(cloth_id=json_data.get("cloth_id", "None"))
        if cloth_object.count() == 0:
            return JsonResponse({"code": -1, "message": f"删除失败：数据库中无此cloth id"})
        cloth_object.first().delete()
        image_path = os.path.join(STATIC_ROOT, IMAGES_URL, json_data.get("cloth_id", "None") + ".JPG")
        image_small_path = os.path.join(STATIC_ROOT, IMAGES_URL, json_data.get("cloth_id", "None") + "_small.JPG")
        if os.path.exists(image_path):
            os.remove(image_path)
        if os.path.exists(image_small_path):
            os.remove(image_small_path)
    except Exception as e:
        return JsonResponse({"code": -1, "message": f"删除失败：{e}"})
    return JsonResponse({"code": 0, "message": f"删除成功"})


def upload_image(request):
    import datetime
    current_time = datetime.datetime.now()
    image_name = (str(current_time).replace("-", "_").replace(" ", "_")
                  .replace(":", "_")).replace(".", "")

    try:
        image = request.FILES.get("file")
        image_path = os.path.join(STATIC_ROOT, IMAGES_URL)
        if os.path.exists(image_path) is False:
            os.mkdir(image_path)
        image_path = os.path.join(STATIC_ROOT, IMAGES_URL, image_name + ".JPG")
        write_image_to_local(image, image_path)
    except Exception as e:
        return JsonResponse({"code": -1, "message": f"图像上传失败：{e}"})
    return JsonResponse({"code": 0, "message": f"{image_name}"})
